package 字符串;

/**
 * @Author Weton Li
 * @Date 2021/4/4 15:25
 */
public class 字符串中的单词数 {

    public static int method1(String s) {

        String trim = s.trim();
        if (trim.equals("")) {
            return 0;
        }
        String[] s1 = trim.split("\\s+");
        return s1.length;
    }

    public static int method2(String s) {

        int n = s.length();
        int count = 0;
        for (int i = 0; i < n; i++) {

//            这里i==0必须放在前面，为此题精华，若为初始字符，则count必加一
            if ( (i == 0||s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
                count++;
            }
        }
        return count;
    }


    public static void main(String[] args) {
        String s = "Hello, my name is John";//
        System.out.println(method1(s));
        System.out.println(method2(s));
    }
}
